博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Airbnb React/JSX 编码规范
阅读量:4641 次
发布时间:2019-06-09

本文共 7370 字,大约阅读时间需要 24 分钟。

Airbnb React/JSX 编码规范

算是最合理的React/JSX编码规范之一了

内容目录

Basic Rules 基本规范

  • 每个文件只写一个模块.
    • 但是多个可以放在单个文件中. eslint: .
  • 推荐使用JSX语法.
  • 不要使用 React.createElement,除非从一个非JSX的文件中初始化你的app.

创建模块

Class vs React.createClass vs stateless

  • 如果你的模块有内部状态或者是refs, 推荐使用 class extends React.Component 而不是 React.createClass ,除非你有充足的理由来使用这些方法.

    eslint:  

    // badconst Listing = React.createClass({    // ...render() {      return 
    {
    this.state.hello}
    ; } }); // goodclass Listing extends React.Component { // ...render() { return
    {
    this.state.hello}
    ; } }

    如果你的模块没有状态或是没有引用refs, 推荐使用普通函数(非箭头函数)而不是类:

    // badclass Listing extends React.Component {    render() {      return 
    {
    this.props.hello}
    ; } } // bad (relying on function name inference is discouraged)const Listing = ({
    hello }) => (
    {
    hello}
    ); // goodfunction Listing({
    hello }) { return
    {
    hello}
    ; }

Naming 命名

  • 扩展名: React模块使用 .jsx 扩展名.
  • 文件名: 文件名使用驼峰式. 如, ReservationCard.jsx.
  • 引用命名: React模块名使用驼峰式命名,实例使用骆驼式命名. eslint: 

    // badimport reservationCard from './ReservationCard';// goodimport ReservationCard from './ReservationCard';// badconst ReservationItem = 
    ;// goodconst reservationItem =
    ;
  • 模块命名: 模块使用当前文件名一样的名称. 比如 ReservationCard.jsx 应该包含名为 ReservationCard的模块. 但是,如果整个文件夹是一个模块,使用 index.js作为入口文件,然后直接使用 index.js 或者文件夹名作为模块的名称:

    // badimport Footer from './Footer/Footer';// badimport Footer from './Footer/index';// goodimport Footer from './Footer';
  • 高阶模块命名: 对于生成一个新的模块,其中的模块名 displayName 应该为高阶模块名和传入模块名的组合. 例如, 高阶模块 withFoo(), 当传入一个 Bar 模块的时候, 生成的模块名 displayName 应该为 withFoo(Bar).

    为什么?一个模块的 displayName 可能会在开发者工具或者错误信息中使用到,因此有一个能清楚的表达这层关系的值能帮助我们更好的理解模块发生了什么,更好的Debug.

    // bad  export default function withFoo(WrappedComponent) {    return function WithFoo(props) {      return 
    ; } } // good export default function withFoo(WrappedComponent) { function WithFoo(props) { return
    ; } const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; WithFoo.displayName = `withFoo(${
    wrappedComponentName})`; return WithFoo; }
  • 属性命名: 避免使用DOM相关的属性来用作其他的用途。

    为什么?对于style 和 className这样的属性名,我们都会默认它们代表一些特殊的含义,如元素的样式,CSS class的名称。在你的应用中使用这些属性来表示其他的含义会使你的代码更难阅读,更难维护,并且可能会引起bug。

    // bad  
    // good

Declaration 声明模块

  • 不要使用 displayName 来命名React模块,而是使用引用来命名模块, 如 class 名称.

    // badexport default React.createClass({  displayName: 'ReservationCard',  // stuff goes here});// goodexport default class ReservationCard extends React.Component {}

Alignment 代码对齐

  • 遵循以下的JSX语法缩进/格式. eslint: 

    // bad
    // good, 有多行属性的话, 新建一行关闭标签
    // 若能在一行中显示, 直接写成一行
    // 子元素按照常规方式缩进

Quotes 单引号还是双引号

  • 对于JSX属性值总是使用双引号("), 其他均使用单引号. eslint: 

    为什么? JSX属性 , 因此在双引号里包括像 "don't" 的属性值更容易输入. HTML属性也是用双引号,所以JSX属性也遵循同样的语法.

    // bad  
    // good
    // bad
    // good

Spacing 空格

  • 总是在自动关闭的标签前加一个空格,正常情况下也不需要换行. eslint: , 

    // bad
    // very bad
    // bad
    // good
  • 不要在JSX {} 引用括号里两边加空格. eslint: 

    // bad
    // good

Props 属性

  • JSX属性名使用骆驼式风格camelCase.

    // bad
    // good
  • 如果属性值为 true, 可以直接省略. eslint: 

    // bad
    // good
  • <img> 标签总是添加 alt 属性. 如果图片以presentation(感觉是以类似PPT方式显示?)方式显示,alt 可为空, 或者<img> 要包含role="presentation". eslint: 

    // bad// goodMe waving hello// good// good
  • 不要在 alt 值里使用如 "image", "photo", or "picture"包括图片含义这样的词, 中文也一样. eslint: 

    为什么? 屏幕助读器已经把 img 标签标注为图片了, 所以没有必要再在 alt 里说明了.

    // bad  Picture of me waving hello  // good  Me waving hello
  • 使用有效正确的 aria role属性值 . eslint: 

    // bad - not an ARIA role
    // bad - abstract ARIA role
    // good
  • 不要在标签上使用 accessKey 属性. eslint: 

    为什么? 屏幕助读器在键盘快捷键与键盘命令时造成的不统一性会导致阅读性更加复杂.

    // bad
    // good
  • 避免使用数组的index来作为属性key的值,推荐使用唯一ID. ()

    // bad{
    todos.map((todo, index) =>
    )}// good{
    todos.map(todo => (
    ))}

Refs

  • 总是在Refs里使用回调函数. eslint: 

    // bad
    // good
    {
    this.myRef = ref; }}/>

Parentheses 括号

  • 将多行的JSX标签写在 ()里. eslint: 

    // badrender() {  return 
    ;}// goodrender() { return (
    );}// good, 单行可以不需要render() { const body =
    hello
    ; return
    {
    body}
    ;}

Tags 标签

  • 对于没有子元素的标签来说总是自己关闭标签. eslint: 

    // bad
    // good
  • 如果模块有多行的属性, 关闭标签时新建一行. eslint: 

    // bad
    // good

Methods 函数

  • 使用箭头函数来获取本地变量.

    function ItemList(props) {  return (    
      {
      props.items.map((item, index) => (
      doSomethingWith(item.name, index)} /> ))}
    );}
  • 当在 render() 里使用事件处理方法时,提前在构造函数里把 this 绑定上去. eslint: 

    为什么? 在每次 render 过程中, 再调用 bind 都会新建一个新的函数,浪费资源.

    // badclass extends React.Component {    onClickDiv() {      // do stuff    }    render() {      return 
    } } // goodclass extends React.Component { constructor(props) { super(props); this.onClickDiv = this.onClickDiv.bind(this); } onClickDiv() { // do stuff } render() { return
    } }
  • 在React模块中,不要给所谓的私有函数添加 _ 前缀,本质上它并不是私有的.

    为什么?_ 下划线前缀在某些语言中通常被用来表示私有变量或者函数。但是不像其他的一些语言,在JS中没有原生支持所谓的私有变量,所有的变量函数都是共有的。尽管你的意图是使它私有化,在之前加上下划线并不会使这些变量私有化,并且所有的属性(包括有下划线前缀及没有前缀的)都应该被视为是共有的。了解更多详情请查看Issue, 和  。

    // badReact.createClass({    _onClickSubmit() {      // do stuff    },    // other stuff  });  // goodclass extends React.Component {    onClickSubmit() {      // do stuff    }    // other stuff  }
  • 在 render 方法中总是确保 return 返回值. eslint: 

    // badrender() {  (
    );}// goodrender() { return (
    );}

Ordering React 模块生命周期

  • class extends React.Component 的生命周期函数:

  1. 可选的 static 方法
  2. constructor 构造函数
  3. getChildContext 获取子元素内容
  4. componentWillMount 模块渲染前
  5. componentDidMount 模块渲染后
  6. componentWillReceiveProps 模块将接受新的数据
  7. shouldComponentUpdate 判断模块需不需要重新渲染
  8. componentWillUpdate 上面的方法返回 true, 模块将重新渲染
  9. componentDidUpdate 模块渲染结束
  10. componentWillUnmount 模块将从DOM中清除, 做一些清理任务
  11. 点击回调或者事件处理器 如 onClickSubmit() 或 onChangeDescription()
  12. render 里的 getter 方法 如 getSelectReason() 或 getFooterContent()
  13. 可选的 render 方法 如 renderNavigation() 或 renderProfilePicture()
  14. render render() 方法

  • 如何定义 propTypesdefaultPropscontextTypes, 等等其他属性...

    import React, {
    PropTypes } from 'react';const propTypes = { id: PropTypes.number.isRequired, url: PropTypes.string.isRequired, text: PropTypes.string,};const defaultProps = { text: 'Hello World',};class Link extends React.Component { static methodsAreOk() { return true; } render() { return {
    this.props.text}
    }}Link.propTypes = propTypes;Link.defaultProps = defaultProps;export default Link;
  • React.createClass 的生命周期函数,与使用class稍有不同: eslint: 

  1. displayName 设定模块名称
  2. propTypes 设置属性的类型
  3. contextTypes 设置上下文类型
  4. childContextTypes 设置子元素上下文类型
  5. mixins 添加一些mixins
  6. statics
  7. defaultProps 设置默认的属性值
  8. getDefaultProps 获取默认属性值
  9. getInitialState 或者初始状态
  10. getChildContext
  11. componentWillMount
  12. componentDidMount
  13. componentWillReceiveProps
  14. shouldComponentUpdate
  15. componentWillUpdate
  16. componentDidUpdate
  17. componentWillUnmount
  18. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
  19. getter methods for render like getSelectReason() or getFooterContent()
  20. Optional render methods like renderNavigation() or renderProfilePicture()
  21. render

isMounted

  • 不要再使用 isMounted. eslint: 

    为什么? , 在 ES6 classes 中无法使用, 官方将在未来的版本里删除此方法.

来源: 

转载于:https://www.cnblogs.com/itlyh/p/6020648.html

你可能感兴趣的文章
Android屏幕适配
查看>>
ps简单操作文档
查看>>
CSS之float样式
查看>>
08test
查看>>
测试用例方法总结
查看>>
基数---SQL Server 2008 Bible
查看>>
第一个JSP程序
查看>>
数组常用的API——splice()截取
查看>>
sbt教程
查看>>
djang1.7 复制粘贴小项目(generic View的使用)
查看>>
Python For Delphi---更好地协同(续)
查看>>
Java的内存泄漏
查看>>
152-PHP htmlspecialchars函数
查看>>
061-PHP函数定义默认参数
查看>>
Genymotion下载模拟器失败解决方案
查看>>
The Apostrophe and the Quote Function ‘和引用函数 未翻译完)
查看>>
kv.go
查看>>
利用截取字符串,生成已声明的字符串中的4位随机验证码。
查看>>
Spring 事务模型
查看>>
【MM系列】SAP S/4 HANA BP创建客户/供应商的一点想法
查看>>